<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 120px;
  line-height: 130px;
  text-align: center;
}

.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  font-size: 24px;
  color: #FF8400;
}

.el-page-header {
  margin: 15px 10px;
}

.el-page-header__title {
  color: #FF8400;
  font-size: 20px;
  font-weight: bolder;
}

.el-page-header__content {
  font-size: 23px;
  font-weight: bold;
}

.avatar {
  width: 130px;
  height: 110px;
  display: block;
}

.el-divider--horizontal {
  margin-top: 30px;
}

.el-input__inner {
  border-color: black;
  height: 70px;
}

.el-dialog__title {
  font-family: 黑体;
  font-size: 25px;
}

.el-dialog__header {
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  size: 100px;
}
.bodyDiv {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
</style>

<template>
  <div class="bodyDiv">
    <el-card style="width: 1200px;height:auto;margin: -19px auto;">
      <div align="center">
        <el-page-header @back="goBack" content="详情页面">
        </el-page-header>
        <h1 style="margin:0 auto;font-size: 30px">{{ forumStandard.title }}</h1>
        <span style="position:relative; left:-30px">{{ forumStandard.gmtCreate }}</span>

        <el-avatar style="position:relative; top:11px; left: -5px" :size="35" shape="circle"
                   :src="forumStandard.userPhoto==null?'':require('../img/user/'+forumStandard.userPhoto)"/>
        <span>{{ forumStandard.username }}</span>
        <el-popconfirm
            @confirm="deleteForum()"
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-info"
            icon-color="red"
            title="确定要删除此论坛吗？">
          <el-button style="margin-left: 20px;margin-right: 10px" slot="reference" type="warning"
                     v-show="forumStandard.isCurrentPublish==1">删除
          </el-button>
        </el-popconfirm>
        <el-button type="primary" @click="openEditDialog()" v-show="forumStandard.isCurrentPublish==1">编辑</el-button>
        <div align="left" v-html="forumStandard.content" style="white-space: pre-line;font-size: 20px;margin:20px 0"/>
        <img v-show="photoShow"
             :src="forumStandard.photo==null || forumStandard.photo<1?'':require('../img/user/'+forumStandard.photo)"
             alt="加载失败"
             style="width: 600px;height: 350px;">
        <el-divider content-position="center"><i style="font-size: 24px;color: #FF8400"
                                                 class="el-icon-chat-dot-square"></i><span
            style="font-size: 24px;color: #FF8400">评论专区</span></el-divider>

        <!--    评论模块    -->
        <el-card style="border-color: #282C30; width: 700px;height: 265px;margin: 30px auto">
          <el-avatar style="float: left; margin-left:5px" :size="50" shape="circle"
                     :src="currentUserPhoto==null || currentUserPhoto<1?'':require('../img/user/'+currentUserPhoto)"/>
          <el-form style="margin:1px 0 0 -33px;" :model="commentForm" status-icon :rules="rules" ref="commentForm"
                   label-width="100px">
            <el-form-item prop="comment">
              <el-input placeholder="我有话要说..." v-model="commentForm.comment" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="图片">
              <el-upload
                  :on-remove="handleRemove"
                  :limit="1"
                  list-type="picture-card"
                  style="text-align: left;"
                  class="avatar-uploader"
                  action="http://localhost:8080/user/upload"
                  :on-success="handleSuccess2"
                  :before-upload="beforeAvatarUpload">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button style="position:relative;top:-85px;float: right;right: 1px"
                         type="danger" @click="addNewComment('commentForm')">发布
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-tabs type="border-card">
          <el-tab-pane label="最新评论">
            <el-row>
              <el-col v-for="comment in commentArr">
                <el-avatar style="float: left; margin-left:5px;margin-top: 1px" :size="50" shape="circle"
                           :src="require('../img/user/'+comment.userPhoto)"/>
                <div align="left" style="margin: 0 0 0 71px">
                  <span style="font-size: 20px;color: #FF8400">{{ comment.username }}</span>
                  <span style="margin-left: 14px;margin-right:10px;color: gray">{{ comment.gmtCreate }}</span>

                  <el-tag v-show="forumStandard.username ==comment.username? true:false"
                          :type="forumStandard.username == comment.username ? 'danger':''">
                    作者
                  </el-tag>
                  <el-tag v-show="comment.username == currentUsername &&forumStandard.username !=comment.username?true:false"
                          :type="comment.username == currentUsername ? 'info':''">
                    我
                  </el-tag>


                  <el-badge :value="comment.countByLike" style="float: right;position: relative;top: 9px">
                    <el-button @click="commentLike(comment)" type="danger" icon="el-icon-star-on" circle size="small">点赞
                    </el-button>
                  </el-badge>
                  <el-popconfirm
                      @confirm="deleteComment(comment)"
                      confirm-button-text='确定'
                      cancel-button-text='取消'
                      icon="el-icon-info"
                      icon-color="red"
                      title="确定要删除此评论吗？">
                    <el-button v-show="comment.username==currentUsername || forumStandard.username==currentUsername"
                               style="float: right;position: relative;top: 9px;left:-7px"
                               slot="reference" size="small">删除
                    </el-button>
                  </el-popconfirm>
                  <br>
                  <span style="position: relative;top: 7px;font-family:楷体">{{ comment.comment }}</span>
                  <br>
                  <img v-show="comment.photo<1?false:true"
                       :src="comment.photo<1?'':require('../img/user/'+comment.photo)"
                       alt="加载失败"
                       style="width: 130px;height: 100px;margin-top:15px">
                </div>
                <el-divider></el-divider>
              </el-col>
            </el-row>
            <div class="block" align="center" style="margin-top: 5px">
              <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page.sync="page"
                  :page-size="pageSize"
                  layout="prev, pager, next, jumper"
                  :total="this.totalCount">
              </el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    <!--  弹出修改论坛的弹框  -->
    <el-dialog @opened="initWangEditor()" :title="'编辑['+forumStandard.title+']'"
               :visible.sync="editFormVisible">
      <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="100px" class="demo-ruleForm">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth">
          <el-input type="textarea" autosize placeholder="请输入标题" maxlength="20" show-word-limit
                    minlength="2" v-model="updateForm.title">
          </el-input>
        </el-form-item>
        <el-form-item label="商品详情">
          <div id="wangEditor" v-html="updateForm.content"></div>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/user/upload"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="this.updateForm.photo" :src="photoUrl!=''?photoUrl:require('../img/user/'+forumStandard.photo)"
                 class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item class="formFoot">
          <el-button style="border-radius: 30px" @click="resetForm('updateForm')">重置</el-button>
          <el-button style="border-radius: 30px" @click="editFormVisible = false">取消</el-button>
          <el-button style="background-color: #008000; border-radius: 30px" type="primary"
                     @click="submitUpdateForm('updateForm')">修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      StandardUserPhoto: '',
      currentUsername: '',
      forumStandardPhoto: '',
      userPhoto: '',
      currentUserPhoto: '',
      photoUrl: "",
      editor: {},
      wangShow: 0,
      photoShow: true,
      forumStandard: {},
      commentArr: [],
      editFormVisible: false,
      formLabelWidth: '75px',
      updateDialogTitle: '',
      updateForm: {
        title: '',
        content: '',
        photo: ''
      },
      commentForm: {
        forumId: '',
        comment: '',
        photo: ''
      },
      rules: {
        title: [
          {required: true, message: '请输入论坛标题', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        comment: [
          {required: true, message: '请输入评论内容', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
        ],
      },
      pageSize: 5,
      page: 1,
      totalCount: 0,
    }
  },
  methods: {
    //撤销上传图片
    handleRemove(file, fileList) {
      console.log("需要移除的文件是" + file, fileList);
      console.log("需要移除的uuid值是" + file.response);
      let url = 'http://localhost:8080/user/uploadDelete/uuid=' + file.response;
      console.log('执行图片撤销的请求路径是：' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: '撤销图片成功！',
            showClose: true,
            position: 'top-right'
          });
          this.commentForm.photo = '';
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
        }
      });
    },
    //返回论坛页面
    goBack() {
      this.$router.push('forum');
    },

    //图片上传成功后
    handleSuccess(response, file) {
      console.log(response);
      this.updateForm.photo = response;
      this.photoUrl = URL.createObjectURL(file.raw);
    },
    handleSuccess2(response) {
      console.log(response);
      this.commentForm.photo = response;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //删除评论
    deleteComment(comment) {
      if (comment.username == this.currentUsername) {
        let url = 'http://localhost:8080/comment/' + comment.id + '/delete';
        console.log('删除自己发表的评论url是' + url);
        this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
            .get(url).then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.$notify.success({
              title: '提示',
              message: "删除成功！",
              showClose: true,
              position: 'top-right'
            });
            this.showCommentList();
          } else {
            this.$notify.warning({
              title: '提示',
              message: responseBody.message,
              showClose: true,
              position: 'top-right'
            });
            this.showCommentList();
          }
        })
      } else if (this.forumStandard.username == this.currentUsername) {
        let forumId = localStorage.getItem('forumStandardId');
        let url = 'http://localhost:8080/comment/' + comment.id + '/' + forumId + '/delete';
        console.log('删除当前用户发布的论坛下的评论url是' + url);
        this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
            .get(url).then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.$notify.success({
              title: '提示',
              message: "删除成功！",
              showClose: true,
              position: 'top-right'
            });
            this.showCommentList();
          } else {
            this.$notify.warning({
              title: '提示',
              message: responseBody.message,
              showClose: true,
              position: 'top-right'
            });
            this.showCommentList();
          }
        })
      }
    },

    //执行评论点赞
    commentLike(comment) {
      let url = 'http://localhost:8080/comment/' + comment.id + '/addLike';
      console.log('给评论点赞url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.showCommentList();
          this.$notify.success({
            title: '提示',
            message: responseBody.data,
            showClose: true,
            position: 'top-right'
          });
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
          this.showCommentList();
        }
      })
    },

    //展示评论列表
    showCommentList() {
      let forumId = localStorage.getItem('forumStandardId');
      let url = 'http://localhost:8080/comment/' + forumId + '/' + this.page + '/' + this.pageSize + '/page';
      console.log('评论列表请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.commentArr = responseBody.data.list;
          this.totalCount = responseBody.data.totalCount;
          this.currentUsername = localStorage.getItem('currentUsername');
        } else {
          this.$router.push('forum');
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
        }
      })
    },

    //发表评论
    addNewComment(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.commentForm.forumId = this.forumStandard.id;
          let formData = this.qs.stringify(this.commentForm);
          console.log(formData);
          let url = 'http://localhost:8080/comment/addNew';
          console.log('发表评论请求URL = ' + url);

          this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              location.reload();
              this.$notify.success({
                title: '提示',
                message: "发布评论成功!",
                showClose: true,
                position: 'top-right'
              });
            } else if (responseBody.state == 40100) {
              this.$router.push('/login');
              this.$notify.warning({
                title: '提示',
                message: responseBody.message,
                showClose: true,
                position: 'top-right'
              });
            } else {
              this.$notify.warning({
                title: '提示',
                message: responseBody.message,
                showClose: true,
                position: 'top-right'
              });
              this.$router.push('forum');
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //打开高级文本编辑框
    initWangEditor() {
      this.wangShow++;
      if (this.wangShow == 1) {
        this.editor = new this.wangEditor('#wangEditor');
        this.editor.config.zIndex = 1;
        this.editor.create();
      }
    },

    //展示论坛详情信息
    showForumStandard() {
      let forumId = localStorage.getItem("forumStandardId");
      let isLogin = localStorage.getItem('userJwt');
      if (isLogin == '') {
        isLogin = 'null';
      }
      let url = 'http://localhost:8080/forum/' + isLogin + '/' + forumId + '/select';
      console.log('论坛详情请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
          .get(url).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.currentUserPhoto = localStorage.getItem('currentUserPhoto');
              this.forumStandard = responseBody.data;
              if (this.forumStandard.photo < 1) {
                this.photoShow = false;
              }
              this.userPhoto = 'http://localhost:8080/images/upload/' + this.forumStandard.userPhoto;
              // this.photoUrl = "http://localhost:8080/images/upload/" + this.forumStandard.photo;
            } else {
              this.$router.push('forum');
              this.$notify.warning({
                title: '提示',
                message: responseBody.message,
                showClose: true,
                position: 'top-right'
              });
            }
          }
      )
    },

    //删除论坛
    deleteForum() {
      let url = 'http://localhost:8080/forum/' + this.forumStandard.id + '/delete';
      console.log('删除论坛url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: "删除[" + this.forumStandard.title + "]成功！",
            showClose: true,
            position: 'top-right'
          });
          this.$router.push('forum');
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
          this.showForumStandard();
        }
      })
    },

    //弹出修改框
    openEditDialog() {
      this.editFormVisible = true;
      this.updateForm.title = this.forumStandard.title;
      this.updateForm.content = this.forumStandard.content;
      this.updateForm.photo = this.forumStandard.photo;
    },

    //提交修改
    submitUpdateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateForm.content = this.editor.txt.html();
          console.log('即将提交到服务端的数据：');
          console.log(this.updateForm);

          let formData = this.qs.stringify(this.updateForm);
          console.log(formData);
          let url = 'http://localhost:8080/forum/' + this.forumStandard.id + '/update';
          console.log('修改请求URL = ' + url);

          this.axios.create({'headers': {'Authorization': localStorage.getItem('userJwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$notify.success({
                title: '提示',
                message: "修改论坛信息成功！等待审核！",
                showClose: true,
                position: 'top-right'
              });
              this.$router.push('forum');
            } else {
              this.$notify.warning({
                title: '提示',
                message: responseBody.message,
                showClose: true,
                position: 'top-right'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.showCommentList();
      console.log(`当前页: ${val}`);
    },
    //清空添加输入框
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.showForumStandard();
    this.showCommentList();
  },
}
</script>